package serverside;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


public class Server {

    ServerSocket welcomeSocket;
    private static final int maxClientsCount = 8;
    private static final ATM[] threads = new ATM[maxClientsCount];
    DataOutputStream os;
    BufferedReader inFromClinet;
    int i;
    public static boolean flag = true;
    public static String[] onlineATMs = new String[maxClientsCount];
    
    public Server() {
        try {
            welcomeSocket = new ServerSocket(6789);
        } catch (IOException ex) {
            System.err.println("An error occured in making the welcome socket");
        }
    }

    public void connect() {
        while (true) {
            try {
                
                Socket connectionSocket = welcomeSocket.accept();
                
                i = 0;
                for (i = 0; i < maxClientsCount; i++) {
                    if (threads[i] == null) {
                        (threads[i] = new ATM(connectionSocket, threads, i)).start();
                        System.out.println("client " + connectionSocket.getInetAddress() + " is connected");
                        break;
                    }
                }//end for loop
                if (i == maxClientsCount) {
                    DataOutputStream os = new DataOutputStream(connectionSocket.getOutputStream());
                    /**
                     * We need to reconfigure the client to this part or it
                     * change the way it behave by making the client wait until
                     * any place become free
                     */
                    os.writeBytes("Server too busy. Try later.");
                    os.close();
                    System.out.println("Client " + connectionSocket.getInetAddress()
                            + "is forced to leave because of trafic");
                    connectionSocket.close();
                }//end if 

            } catch (IOException ex) {
                System.err.println("Error in accepting connection\n");
                ex.printStackTrace();
            }
        }//end while loop 
    }//end connect 

}
